import React, { PureComponent } from 'react';
import moment from 'moment';
import { List, Spin ,Button,Avatar,notification,Row,Col,Modal   } from 'antd';
import styles from './index.less';
const sourceMap = ['微信', 'APP','平台发布','webApp'];
const radioImageSrcs = [require("../../../../public/audioImage3.png"),require("../../../../public/audioImage4.gif") ];
var timer = null;
class MsgList extends PureComponent {
  state = {
    replayMessageValue:"",
    audioSrc:"",
    videoSrc:"",
    imageSrc:"",
    msgId:"",
    playbackRate:1.0,
    videoVisible: false,
    iamgeVisible:false,
    radioValue:1.0,
    imageLoading:true,
    imgStyle:{width:20,height:20,marginLeft:20,cursor:"pointer"}
  };

  componentWillReceiveProps(nextProps){
    if(nextProps.radioValue !== undefined && nextProps.radioValue != this.props.radioValue && nextProps.radioValue != this.state.radioValue){
      this.setState({
        radioValue: nextProps.radioValue
      },() => {
        var audio = this.refs.audioMusicPlay;
        audio.playbackRate = this.state.radioValue;
      })
    }
  }
  /**
   * 主播/导播点击播放音乐按钮
   * @param id
   * @param msgAttSrc
   */
  handleMusicPlay = (id,msgAttSrc) => {
    const radioValue = this.state.radioValue;
    var audio = this.refs.audioMusicPlay;

    const msgId = this.state.msgId;
    var curMsgRadioListItem =  document.getElementById("radioImageId"+id);
    var oldMsgRadioListItem = document.getElementById("radioImageId"+msgId);
    if(oldMsgRadioListItem != undefined && msgId != id){
      oldMsgRadioListItem.src = radioImageSrcs[0];
    }
    //设置好id和src
    this.setState({
      msgId:id,
      audioSrc:msgAttSrc,
    },() => {
      audio.onended = function () {
        curMsgRadioListItem.src = radioImageSrcs[0];
      }
      audio.playbackRate = radioValue;
      //如果ID不相等，一定是播放，如果ID相等则取反
      //true 指示音频/视频已暂停
      if(msgId != id){
        curMsgRadioListItem.src = radioImageSrcs[1];
        audio.play();
      }else {
        if(audio.paused){
          curMsgRadioListItem.src = radioImageSrcs[1];
          audio.play();
        }else{
          curMsgRadioListItem.src = radioImageSrcs[0];
          audio.pause();
        }
      }
    });
    event.stopPropagation();
  }

  /**
   * 主播/导播 播放视频    关闭 Modal
   * @param id
   * @param msgAttSrc
   */
  handleMoviePlay = (id,msgAttSrc) => {
    var audio = this.refs.audioMusicPlay;
    //如果音乐没有关，先关闭
    if(!audio.paused){
      var curMsgRadioListItem =  document.getElementById("radioImageId"+self.state.msgId);
      if(curMsgRadioListItem != undefined){
        curMsgRadioListItem.src = radioImageSrcs[0];
      }
      audio.pause();
    }
    this.setState({
      msgId:id,
      videoSrc:msgAttSrc,
      videoVisible:true
    });
    event.stopPropagation();
  }
  handleCancelVideoModal= () => {
    var video = this.refs.videoMoviePlay;
    video.pause();
    this.setState({
      videoVisible:false
    });
  }
  /**
   * 主播/导播 查看图片 关闭图片Modal
   * @param imageSrc
   */
  handleImagePlay = (imageSrc) => {
    var audio = this.refs.audioMusicPlay;
    //如果音乐没有关，先关闭
    if(!audio.paused){
      var curMsgRadioListItem =  document.getElementById("radioImageId"+self.state.msgId);
      if(curMsgRadioListItem != undefined){
        curMsgRadioListItem.src = radioImageSrcs[0];
      }
      audio.pause();
    }
    this.setState({
      imageSrc:imageSrc,
      iamgeVisible:true
    });
    event.stopPropagation();
  }
  handleCancelImageModal= () => {
    this.setState({
      iamgeVisible:false,
    });
  }

  /**
   * 单击显示详细信息
   * @param record
   * @param index
   */
  handleOnClick = (record,index) => {
    console.log("handleOnClick=========="+index);
    clearTimeout(timer);
    var self = this;
    timer = setTimeout(function() {
      var curMsgRadioListItem =  document.getElementById("radioImageId"+self.state.msgId);
      if(curMsgRadioListItem != undefined && self.state.msgId != record.id){
        curMsgRadioListItem.src = radioImageSrcs[0];
      }
      var msgListItems =  document.getElementsByName("msgListName");
      var curMsgListItem =  document.getElementById("msgListId"+index);
      for(var i =0 ; i < msgListItems.length ; i++){
        msgListItems[i].style.removeProperty("background");
      }
      curMsgListItem.style.background = "#e6f7ff";
      self.props.handleOnClick(record,index);
    }, 300);
  }
  /**
   * 双击直接通过
   * @param record
   * @param index
   */
  handleOnDoubleClick = (record,index) => {
    clearTimeout(timer);
    this.props.handleOnDoubleClick(record,index);
  }

  /**
   * 点击通过按钮
   * @param event
   * @param record
   * @param index
   */
  handlePassClick = (event,record,index) => {
    this.props.handlePassClick(record,index);
    event.stopPropagation();
  }
  /**
   * 点击忽略按钮
   * @param event
   * @param record
   * @param index
   */
  handleIgnoreClick = (event,record,index) => {
    this.props.handleIgnoreClick(record,index);
    event.stopPropagation();
  }

  changeLoading(){
    this.setState({
      imageLoading:false,
      imgStyle:{width:60,height:60,marginLeft:0,cursor:"pointer"}
    })
  }

  generateContentDiv = (record) => {
    /*文本内容*/
    if(record.msgContentType == 0){
      return (
        <div style={{marginLeft:12}}>
          {record.msgAttachmentAddr}
        </div>
      );
      /*语音内容*/
    }else if(record.msgContentType == 1){

      return (
        <div style={{marginLeft:12}}>
          <div onClick={() => this.handleMusicPlay(record.id,record.msgAttachmentAddr)} style={{float:"left", height:26,width:135,backgroundImage:"url("+require("../../../../public/audioImage.png")+")",cursor:"pointer" }}>
            <img src={radioImageSrcs[0]} name="radioImageName" id={"radioImageId"+record.id} style={{marginLeft:10, height:26,width:26}}/>
          </div>
          <div style={{float:"left",marginTop:3}}>{record.radioLen > 60 ? 60 : record.radioLen}"</div>
        </div>
      );
      /*图片内容*/
    } else if(record.msgContentType == 2){
      return (
        <div style={{marginLeft:12}}>
          <img  onLoad={()=>this.changeLoading()} src={this.state.imageLoading?require('../../../../public/loading.gif'):record.msgAttachmentAddr} style={this.state.imgStyle}  onClick={() => this.handleImagePlay(record.msgAttachmentAddr) } >
          </img>
        </div>
      );
      /*视频内容*/
    }else if(record.msgContentType == 4){
      return (
        <div style={{marginLeft:12}}>
          <div >
            <img src={require("../../../../public/video.png")} style={{marginLeft:5, height:32,width:32,cursor:"pointer" }} onClick={() => this.handleMoviePlay(record.id,record.msgAttachmentAddr)} />
          </div>
        </div>
      );
    }

  }

  render() {
    const { userType,loading,loadingMore,showLoadingMore,data} = this.props;
    const {audioSrc,videoSrc,imageSrc,videoVisible,iamgeVisible} = this.state;
    const actionsTitle = userType == 1 ? "通过" : "已播" ;
    const loadMore = showLoadingMore ? (
      <div style={{ textAlign: 'center', marginTop: 12, height: 32, lineHeight: '32px' }}>
        {loadingMore && <Spin />}
        {!loadingMore && <Button onClick={() => this.props.onLoadMore() }>加载更多....</Button>}
      </div>
    ) : null;
    return (
      <div >
          <List
            className={styles.msgList}
            loading={loading}
            itemLayout="horizontal"
            loadMore={loadMore}
            dataSource={data}
            header={<Row gutter={24} style={{textAlign:"center"}}>
                      <Col xl={5} lg={24} md={24} sm={24} xs={24}>
                        <div >用户</div>
                      </Col>
                      <Col xl={4} lg={24} md={24} sm={24} xs={24}>
                        <div >消息内容</div>
                      </Col>
                      <Col xl={12} lg={24} md={24} sm={24} xs={24}>
                        <div >自动翻译</div>
                      </Col>
                      <Col xl={3} lg={24} md={24} sm={24} xs={24}>
                        <div >操作</div>
                      </Col>
                  </Row>
            }
            renderItem={(item,index) => (
              <List.Item  name="msgListName" id={"msgListId"+index} className={styles.backgroundMsgRowColor} actions={[<a onClick={(event) => this.handlePassClick(event,item,index)}>{actionsTitle}</a>, <a onClick={(event) => this.handleIgnoreClick(event,item,index)} >忽略</a>] }  onClick={() => this.handleOnClick(item,index)} onDoubleClick={() => this.handleOnDoubleClick(item,index)} >
                <List.Item.Meta
                  avatar={<Avatar src={item.headimgurl} />}
                  title={<span >{item.nickname}</span>}
                  description={<div>来自<span  style={{color:'#808080',fontSize:12}}> {sourceMap[item.messageFrom]} </span><span style={{color:'#808080',fontSize:12 }}>{moment(item.msgTime).format('YYYY-MM-DD HH:mm:ss')}</span></div>}
                />
                <div style={{width:"100%"}}>
                  <Row gutter={24}>
                    <Col xl={10} lg={24} md={24} sm={24} xs={24}>
                      {this.generateContentDiv(item)}
                    </Col>
                    <Col xl={14} lg={24} md={24} sm={24} xs={24}>
                      <div style={{wordWrap:"break-word" }}>{item.msgTxtContent}</div>
                    </Col>
                  </Row>
                </div>
              </List.Item>
            )}
          />
          <div>
           {/* 音乐播放组件*/}
            <audio ref="audioMusicPlay"
                   style={{display:"none"}}
                   src={audioSrc}
                   preload={"auto"}
            >
              您当前的浏览器不支持该播放控件
            </audio>
           {/* 视频播放组件*/}
            <Modal
              visible={videoVisible}
              maskClosable={true}
              footer={null}
              onCancel={this.handleCancelVideoModal}
              width={560}
            >
              <video controls="controls" ref="videoMoviePlay"  style={{width:512,height:488}}>
                <source  src={videoSrc}  type="video/mp4" />
                您的浏览器不支持 video 标签。
              </video>
            </Modal>
            <Modal
              visible={iamgeVisible}
              footer={null}
              onCancel={this.handleCancelImageModal}>
              <img alt="example" style={{ width: '100%' }} src={imageSrc} />
            </Modal>
          </div>
      </div>
    );
  }
}

export default MsgList;
